package com.xhorse.lockplatform.comm.util;

import com.google.gson.Gson;
import com.xhorse.lockplatform.comm.model.ResponseLocation;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 请求工具类
 *
 * @author Stay
 */
public final class RequestUtils {

    private RequestUtils() {
    }

    /**
     * 获取请求客户端IP
     *
     * @param request
     * @return
     */
    public static String getRemoteIp(HttpServletRequest request) {
        String address = request.getHeader("X-Real-IP");
        if (StringUtil.isNotNil(address) && !"unknown".equalsIgnoreCase(address)) {
            return address;
        }
        address = request.getHeader("X-Forwarded-For");
        if (StringUtil.isNotNil(address) && !"unknown".equalsIgnoreCase(address)) {
            return address;
        }
        address = request.getHeader("Proxy-Client-IP");
        if (StringUtil.isNotNil(address) && !"unknown".equalsIgnoreCase(address)) {
            return address;
        }
        address = request.getHeader("WL-Proxy-Client-IP");
        if (StringUtil.isNotNil(address) && !"unknown".equalsIgnoreCase(address)) {
            return address;
        }
        return request.getRemoteAddr();
    }

    public static ResponseLocation getAdd(String longtitude,
                                          String latitude) throws IOException {
        String url = "http://api.map.baidu.com/geocoder/v2/?ak=WEc8RlPXzSifaq9RHxE1WW7lRKgbid6Y&location="
                + latitude + "," + longtitude + "&output=json&pois=0";
        HttpClientUtil httpClientUtil = HttpClientUtil.getInstance();
        RequestBody requestBody = new FormBody.Builder().build();
        Request request = new Request.Builder().url(url).post(requestBody)
                .build();
        Response response = httpClientUtil.getClient().newCall(request).execute();
        String result = String.valueOf(response.body());
        // 将获得的json数据转换成地址对象
        Gson gson = new Gson();
        ResponseLocation location = gson.fromJson(result,
                ResponseLocation.class);
        return location;
    }
}
